import each, { isArrayLike } from './each'
import valyes from '../object/values'
import { cb } from '../util/iteratee';

/**
 *
 *返回list中的最大值。如果传递iteratee参数，iteratee将作为list中每个值的排序依据。如果list为空，将返回-Infinity，所以你可能需要事先用isEmpty检查 list 。
 */
export default function max(obj: any[], iteratee?, context?) {
  var result = -Infinity;
  var lastComputed = -Infinity
  var value
  var commputed
  if (iteratee == null || typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null) {
    obj = isArrayLike(obj) ? obj : valyes(obj)
    for (var i = 0, length = obj.length; i < length; i++) {
      value = obj[i]
      if (value != null && value > result) {
        result = value
      }
    }
  } else {
    iteratee = cb(iteratee, context)
    each(obj, function (v, index, list) {
      commputed = iteratee(v, index, list)
      if (commputed > lastComputed || commputed === -Infinity && result === -Infinity) {
        result = v
        lastComputed = commputed
      }
    })
  }
  return result
}